package com.boot.config;

import com.alibaba.fastjson.JSONObject;
import com.boot.config.result.Model;
import com.boot.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;

/**
 * @Description: 全局异常处理
 * @Author: HuangX
 * @Date: 2021/3/4
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    public static Model PROCESS_ERROR(HttpServletRequest request, Exception ex) {
        Map<String, Object> r = new LinkedHashMap<>();
        String msg;

        if (ex instanceof MethodArgumentNotValidException) {
            //验证失败
            msg = "validate error";
            BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                r.put(fieldError.getObjectName(), fieldError.getDefaultMessage());
            }

        } else if (ex instanceof BindException) {
            msg = "validate error";
            BindingResult bindingResult = ((BindException) ex).getBindingResult();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                 r.put(fieldError.getObjectName(), fieldError.getDefaultMessage());
            }

        } else if (ex instanceof DuplicateKeyException) {
            msg = "DuplicateKeyException";
            log.error(request.getRequestURI(), ex);
            HttpUtils.currentResponse().setStatus(500);

        } else if (ex instanceof HttpMessageNotReadableException) {
            //json
            msg = "json convert failure!";
            log.error(request.getRequestURI(), ex);
            HttpUtils.currentResponse().setStatus(500);

        } else {
            //其他异常
            log.error(ex.toString(), ex);
            HttpUtils.currentResponse().setStatus(500);
            Enumeration<String> enuma = request.getHeaderNames();
            Map<String, Object> vl = new LinkedHashMap<>();
            while (enuma.hasMoreElements()) {
                String key = enuma.nextElement();
                vl.put(key, request.getHeader(key));
            }

            msg = ex.getMessage();
            if (msg.startsWith("com.alibaba.excel.exception.ExcelAnalysisException: ")) {
                msg = msg.replace("com.alibaba.excel.exception.ExcelAnalysisException: ", "");
            } else if (msg.startsWith("java.lang.RuntimeException:")) {
                msg = msg.replace("java.lang.RuntimeException: ", "");
            }

            StringWriter sw = new StringWriter();
            try (PrintWriter pw = new PrintWriter(sw)) {
                ex.printStackTrace(pw);
                r.put("errorTrace", sw.toString());
            }

            r.put("errorMsg", msg);
            r.put("Headers", JSONObject.toJSONString(vl));
            r.put("ServerName", request.getServerName());
            r.put("Host", request.getHeader("Host"));
            r.put("url",
                    request.getScheme() + "://" + request.getHeader("Host") + request.getRequestURI());
        }

        return Model.newFail(msg, (Object) r);
    }

    @ExceptionHandler(Exception.class)
    public Model handleError(HttpServletRequest request, Exception ex) {
        val uri = request.getRequestURI();
        log.error("出错了:", ex);
//        if (uri.endsWith(".html") || uri.endsWith(".htm")) {
//            return new ModelAndView("/error/500.ftl");
//        }
        return PROCESS_ERROR(request, ex);

    }
}
